package com.song.mall.member.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 宋超
 * HP - the login name of the current user.
 * 2021/10/10 - the current system date.
 * 15:39 - the current system time.
 * 解决feign远程调用丢去请求头的问题
 */
@Configuration
public class MyFeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //1、RequestContextHolder拿到刚进来的请求数据
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes!=null) {
                    HttpServletRequest request = attributes.getRequest();//老请求
                    if (request != null) {
                        //2、同步请求数据 Cookie
                        String cookie = request.getHeader("Cookie");
                        requestTemplate.header("Cookie", cookie);
                        System.out.println("feign远程之前先进行requestInterceptor.apply");
                    }
                }
            }
        };
    }
}
